﻿using IApplicationServices;
using Microsoft.Extensions.Configuration;
using RabbitMQ.Client;
using System.Text;
using System.Text.Json;

namespace ApplicationService
{
    public class RabbitMQService:IRabbitMQService
    {
        private readonly IConnection _connection;
        private readonly RabbitMQ.Client.IModel _channel;

        public RabbitMQService(IConfiguration config)
        {
            var factory = new ConnectionFactory();
            factory.HostName = "127.0.0.1";
            factory.Port = 5672;//5672是RabbitMQ默认的端口号
            factory.UserName = "admin";
            factory.Password = "admin";
            factory.VirtualHost = "my_vhost";
            _connection = factory.CreateConnection();
            _channel = _connection.CreateModel();
            _channel.QueueDeclare(queue: "notifications_queue", durable: true, exclusive: false);
        }

        public void Publish(string queue, object message)
        {
            var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));
            _channel.BasicPublish(exchange: "", routingKey: queue, body: body);
        }
    }
}
